package com.my.screenadapter.eventBus.eventBusDemo;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;

import org.greenrobot.eventbus.EventBusException;

import java.util.LinkedList;

/**
 * Created by zhangyingjie on 2019-07-27
 *
 * @function
 */
public class MyHandlerPoster extends Handler {
    private static final String TAG = "MyHandlerPoster";

    LinkedList<UserEvent> queue = new LinkedList<>();

    public MyHandlerPoster(Looper looper) {
        super(looper);
    }

    public void post(UserEvent event){
        queue.add(event);
        if (!sendMessage(obtainMessage())) {
            throw new EventBusException("Could not send handler message");
        }

    }

    @Override
    public void handleMessage(Message msg) {
        try {

            while (true){
                long started = SystemClock.uptimeMillis();
                UserEvent poll = queue.poll();
                if (poll != null ) {
                    Log.i(TAG, "handleMessage: "+Thread.currentThread().getName()
                            +" "+poll.toString());
                    return;
                }

                long timeInMethod = SystemClock.uptimeMillis() - started;
                if (timeInMethod >= 10) {
                    if (!sendMessage(obtainMessage())) {
                        throw new EventBusException("Could not send handler message");
                    }
                    return;
                }
            }
        }finally {
            Log.i(TAG, "handleMessage: finally");
        }

    }
}
